import React, { Component, Fragment } from 'react';
import { connect } from 'dva';

import moment from 'moment';
import { isEqual } from 'lodash';

import { upload } from '@/utils/request';
import { Form } from '@ant-design/compatible';

import {
  Card,
  Col,
  Input,
  Row,
  Select,
  Radio,
  DatePicker,
  Cascader,
  Upload,
  message,
  Button,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';

import { base_url } from '../../../../../../config/request.config';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;
interface BasicInfoProps {
  INITINFO?: any;
  detail?: any;
  partnersAndSubject?: any;
  contractTypeDetail?: any;
  is_contract_num?: number;
  contractType: number;
  contractId: number | string;
  selectContractType: any;
  fetchAction: any;
  forms: any;
  mergeFun: (name: string, value: any) => void;
}

interface BasicInfoState {
  fcs_id: number;
  fileList: any;
  file_link: string;
  currentMerchants: number;
  isExclusive: number;
}

@connect(({
  franchiseeContractEditor: {
    detail,
    contractTypeDetail,
    partnersAndSubject,
    is_contract_num,
  },
  common: { INITINFO },
}: any) => ({
  detail,
  contractTypeDetail,
  partnersAndSubject,
  is_contract_num,
  INITINFO,
}))

class BasicInfoElem extends Component<BasicInfoProps, BasicInfoState> {
  state: BasicInfoState = {
    fcs_id: 0,
    fileList: [],
    file_link: '',
    currentMerchants: 0,
    isExclusive: 1,
  };

  static getDerivedStateFromProps(nextProps: BasicInfoProps, preState: BasicInfoState) {
    const {
      detail,
      detail: { file_link },
      contractType,
      contractTypeDetail,
    } = nextProps;
    const { fcs_id } = preState;

    if (contractTypeDetail.fcs_info) {
      const { region_info } = contractTypeDetail.fcs_info;
      const is_exclusive = region_info ? region_info.is_exclusive : 0;
      return ({
        isExclusive: is_exclusive,
      });
    }

    if (detail.fcs_id && contractType && detail.fcs_id !== fcs_id) {
      return ({
        fcs_id: detail.fcs_id,
      });
    }

    if (!isEqual(file_link, preState.file_link) && file_link) {
      nextProps.mergeFun('file_link', file_link);
      return {
        fileList: [{
          url: file_link,
          uid: '1234',
          name: '点击查看合同',
        }],
        file_link,
      };
    }

    return null;
  }

  // 选择合作商
  handleMerchants = (fcs_id: number) => {
    const { fetchAction, contractType: contract_type } = this.props;
    this.setState({ currentMerchants: fcs_id }, () => {
      if (contract_type) {
        const params = { fcs_id, contract_type };
        fetchAction('fetchContractType', params);
      }
    });
  }

  // 选择合同类型
  handleSelectContractType = (contract_type: number) => {
    const { currentMerchants: fcs_id } = this.state;
    const { selectContractType, fetchAction } = this.props;

    selectContractType(contract_type);

    const params = { fcs_id, contract_type };
    if (fcs_id !== 0) fetchAction('fetchContractType', params);
  }

  // 选择绑定销售合同
  handleBinding = (contract_id: number) => {
    const { fetchAction } = this.props;
    fetchAction('fetchTotalM', { contract_id });
  }

  handleCheck = (e: any) => {
    const { fetchAction } = this.props;
    const contract_num = e.target.value;
    const params = {
      fcs_info: { id: 1 },
      contract_type: 1,
      contract_num,
    };

    if (contract_num) fetchAction('check', params);
  }

  handleCascader = (code: any) => {
    const { mergeFun } = this.props;
    mergeFun('franchise_region', `${code[0]}#${code[1]}#${code[2]}`);
  }

  handleUpload = ({ file }: any) => {
    const fileList = [{
      uid: 1,
      name: file.name.length > 5
        ? `${file.name.substring(0, 5)}....pdf`
        : file.name,
      url: file.url,
    }];
    this.setState({ fileList });
  };

  // 上传合同
  startUpload(value: any) {
    const formData = new FormData();
    formData.append('file', value);

    upload(`${base_url}/franchise/franchisee/upload_file`, { body: formData })
      .then(({ code, body, msg }) => {
        if (code === 0) {
          message.success('上传成功');

          const { fileList } = this.state;
          fileList[0].url = body;

          const { mergeFun } = this.props;
          this.setState({ fileList }, () => mergeFun('file_link', body));
        } else {
          message.error(msg);
        }
      });
  }

  render() {
    const {
      detail,
      contractTypeDetail,
      contractTypeDetail: { fcs_info, sale_contract_list },
      forms: { getFieldDecorator },
      contractType,
      contractId,
      selectContractType,
      is_contract_num,
      partnersAndSubject: { partners, subject },
      INITINFO: { addressList },
    } = this.props;

    const { fileList, isExclusive } = this.state;

    const props: any = {
      action: '',
      onChange: this.handleUpload,
      beforeUpload: this.startUpload.bind(this),
    };

    return (
      <Card title="基本信息" bordered={false} className="paddingB10">
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="所属商户" colon={false}>
              {getFieldDecorator('fcs_id', {
                initialValue: detail.fcs_id,
                rules: [{ required: true, message: '请选择所属商户' }],
              })(
                <Select
                  placeholder="请选择"
                  showSearch
                  disabled={!!contractType && !!contractId}
                  onChange={this.handleMerchants}
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {partners && partners.map((item: any) => (
                    (item.status === 1
                      && <Option value={item.id} key={item.id}>{item.name}</Option>
                    )
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="合同类型" colon={false}>
              {getFieldDecorator('contract_type', {
                initialValue: contractType,
                rules: [{ required: true, message: '请选择合同类型' }],
              })(
                <Select
                  placeholder="请选择"
                  disabled={!!contractType && !!contractId}
                  onSelect={selectContractType}
                  onChange={this.handleSelectContractType}
                >
                  <Option value={1}>加盟合同</Option>
                  <Option value={2}>销售合同</Option>
                  <Option value={3}>借贷合同</Option>
                </Select>,
              )}
            </Item>
          </Col>
          {contractType === 1 && (
            <Col md={8} sm={24}>
              <Item label="加盟性质" colon={false}>
                {getFieldDecorator('is_exclusive', {
                  initialValue: detail.is_exclusive || isExclusive,
                  rules: [{ required: true, message: '请选择加盟性质' }],
                })(
                  <Radio.Group>
                    <Radio value={1}>独家</Radio>
                    <Radio value={0}>非独家</Radio>
                  </Radio.Group>,
                )}
              </Item>
            </Col>
          )}
        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="合同主体" colon={false}>
              {getFieldDecorator('party_a_name', {
                initialValue: detail.party_a_name,
                rules: [{ required: true, message: '请选择合同主体' }],
              })(
                <Select placeholder="请选择">
                  {subject && subject.map(
                    (item: any, index: number) => (
                      <Option value={item} key={item}>{item}</Option>
                    ),
                  )}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="合同编号" colon={false}>
              {getFieldDecorator('contract_num', {
                initialValue: detail.contract_num || contractTypeDetail.contract_num,
                rules: [{ required: true, message: '请输入合同编号' }],
              })(
                <Input
                  allowClear
                  style={{ width: '100%' }}
                  placeholder="请输入"
                  disabled={Boolean(is_contract_num)}
                  onBlur={this.handleCheck}
                />,
              )}
            </Item>
          </Col>
          {contractType === 1 && (
            <Col md={8} sm={24}>
              <Item label="乙方名称" colon={false}>
                {getFieldDecorator('party_b_name', {
                  initialValue: (fcs_info && fcs_info.name) || detail.party_b_name,
                  rules: [{ required: true, message: '请输入乙方名称' }],
                })(
                  <Input allowClear style={{ width: '100%' }} placeholder="请输入" />,
                )}
              </Item>
            </Col>
          )}
          {contractType === 3 && (
            <Col md={8} sm={24}>
              <Item label="绑定销售合同" colon={false}>
                {getFieldDecorator('sale_contract_id', {
                  initialValue: detail.sale_contract_id,
                  rules: [{ required: true, message: '请选择绑定销售合同' }],
                })(
                  <Select
                    placeholder="请选择"
                    onChange={this.handleBinding}
                  >
                    {sale_contract_list && sale_contract_list.map((item: any, index: number) => (
                      <Option value={item.id} key={item.id}>{item.contract_num}</Option>
                    ))}
                  </Select>,
                )}
              </Item>
            </Col>
          )}
        </Row>
        {contractType === 1 && (
          <Fragment>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Item label="合同周期" colon={false}>
                  {getFieldDecorator('momentTime', {
                    initialValue: detail.start_time && [
                      moment(detail.start_time.split(' --- ')[0], 'YYYY-MM-DD'),
                      moment(detail.start_time.split(' --- ')[1], 'YYYY-MM-DD'),
                    ],
                    rules: [{ required: true, message: '请选择合同周期' }],
                  })(<RangePicker
                    format="YYYY/MM/DD"
                    style={{ width: '100%' }}
                  />)}
                </Item>
              </Col>

              <Col md={8} sm={24}>
                <Item label="　联系人" colon={false}>
                  {getFieldDecorator('party_b_contact', {
                    initialValue: (fcs_info && fcs_info.contact) || detail.party_b_contact,
                    rules: [{ required: true, message: '请输入联系人' }],
                  })(
                    <Input allowClear style={{ width: '100%' }} placeholder="请输入" />,
                  )}
                </Item>
              </Col>

              <Col md={8} sm={24}>
                <Item label="联系电话" colon={false}>
                  {getFieldDecorator('party_b_phone', {
                    initialValue: (fcs_info && fcs_info.phone) || detail.party_b_phone,
                    rules: [{ required: true, message: '请输入联系人手机' }],
                  })(
                    <Input allowClear style={{ width: '100%' }} placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>

            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Item label="加盟区域" colon={false}>
                  {getFieldDecorator('franchise_region', {
                    initialValue: (detail.franchise_region && [
                      detail.franchise_region.split('#')[0],
                      detail.franchise_region.split('#')[1],
                      detail.franchise_region.split('#')[2],
                    ]) || (contractTypeDetail.fcs_info && [
                      contractTypeDetail.fcs_info.region_info.parea_code,
                      contractTypeDetail.fcs_info.region_info.carea_code,
                      contractTypeDetail.fcs_info.region_info.darea_code,
                    ]),
                    rules: [{ required: true, message: '请选择加盟区域' }],
                  })(
                    <Cascader
                      options={addressList}
                      placeholder="请选择"
                      onChange={this.handleCascader}
                    />,
                  )}
                </Item>
              </Col>

              <Col md={8} sm={24}>
                <Item label="乙方住所" colon={false}>
                  {getFieldDecorator('party_b_address', {
                    initialValue: (fcs_info && fcs_info.address) || detail.party_b_address,
                    rules: [{ required: true, message: '请输入乙方住所' }],
                  })(
                    <Input allowClear style={{ width: '100%' }} placeholder="请输入" />,
                  )}
                </Item>
              </Col>

              <Col md={8} sm={24}>
                <Item label="上传合同" colon={false}>
                  {getFieldDecorator('file_link', {
                    initialValue: detail.file_link,
                    rules: [{ required: true, message: '请上传合同文件' }],
                  })(
                    <Upload
                      accept=".pdf"
                      {...props}
                      fileList={fileList}
                    >
                      <Button
                        type="primary"
                        ghost
                        style={{ fontSize: 12 }}
                        size="small"
                      >
                        <UploadOutlined />
                        上传文件
                      </Button>
                    </Upload>,
                  )}
                </Item>
              </Col>
            </Row>
          </Fragment>
        )}
      </Card>
    );
  }
}

export default BasicInfoElem;
